package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        //1.通过Httpclient向wx平台发送请求.接受响应数据
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("appid",weChatProperties.getAppid());
        paramMap.put("secret",weChatProperties.getSecret());
        paramMap.put("js_code",userLoginDTO.getCode());
        paramMap.put("grant_type","authorization_code");
        String respond = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", paramMap);

        //2.解析响应数据
        JSONObject jsonObject = JSON.parseObject(respond);
        String openId = (String) jsonObject.get("openid");

        if (openId == null)
        {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //3.查询数据库是否有此openId，有则返回，无则创建
        User user = userMapper.selectByOpenId(openId);

        if (user == null)
        {
            user = User.builder()
                    .openid(openId)
                    .name(openId.substring(0,5))
                    .createTime(LocalDateTime.now())
                    .build();

            userMapper.insertByUser(user);
        }

        return user;
    }
}
